<?php
/**
 * Created by PhpStorm.
 * desc:
 * User: wang.yizhe
 * Date: 2023/12/6
 * Time: 19:37
 */

namespace App\Repositories;

use App\Models\WxUsersModel;

class WxUsersRepository
{


    protected $buildQueryObj; //查询资源

    /**
     * 构建查询条件
     * @param $query
     * @return true
     */
    public function buildQuery($query = [])
    {
        $where = [];
        $whereIn = [];
        if (!empty($query['id'])) {
            $where[] = ['id', $query['id']];
        }
        if (!empty($query['ids'])) {
            $whereIn[] = ['id', $query['ids']];
        }
        if (!empty($query['openid'])) {
            $where[] = ['openid', $query['openid']];
        }
        if (!empty($query['openids'])) {
            $whereIn[] = ['openid', $query['openids']];
        }

        $this->buildQueryObj = WxUsersModel::query()
            ->where($where);
        foreach ($whereIn as $val) {
            $this->buildQueryObj->whereIn($val[0], $val[1]);
        }
        //强制使用主库
        if (!empty($query['useMaster'])) {
            $this->buildQueryObj->lock();
        }

        return true;
    }


    /**
     * 获取列表
     * @return mixed
     */
    public function getRow()
    {
        return $this->buildQueryObj
            ->first();
    }

    /**
     * 获取列表
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function getList($offset = 0, $limit = 20, $orderType = 0)
    {
        $res = $this->buildQueryObj
            ->offset($offset)
            ->limit($limit);
        if ($orderType) {
            switch ($orderType) {
                case 1:
                    break;
            }
        } else {
            $res->orderBy('created_at', 'desc');
        }

        return $res->get();
    }

    public function getTotal()
    {
        return $this->buildQueryObj
            ->count();
    }

    /**
     * 保存
     * @param $query
     * @return array
     */
    public function save($data = [])
    {
        $saveData = [
            'openid' => $data['openid'], //微信用户唯一标识id
            'name'   => $data['name'] ?? '', //微信名称
            'pic'    => $data['pic'] ?? '', //微信头像
        ];
        $lastId = WxUsersModel::query()
            ->insertGetId($saveData);
        if (!$lastId) {
            return false;
        }

        return $lastId;
    }


    /**
     * 更新字段值
     * @param $id
     * @param $fields
     * @return false
     */
    public function updateFields($id, $fields = [])
    {
        if (!$fields) {
            return false;
        }
        //取出对应资源
        $this->buildQuery([
            'id' => $id,
        ]);
        $relation = $this->getRow();
        if (!$relation) {
            return false;
        }
        //拼装修改字段
        foreach ($fields as $field => $val) {
            $relation->$field = $val;
        }
        return $relation->save();
    }

}
